//
//  SLCATextLayerController.m
//  Objective-C
//
//  Created by S_Line on 2018/6/29.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "SLCATextLayerController.h"

#import <CoreText/CoreText.h>

@interface SLCATextLayerController ()

@end

@implementation SLCATextLayerController

- (void)initNavBar {
    self.navTitle = @"CATextLayer";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavBar];
    
    [self initView];
}

- (void)initView {
    CGFloat labelMarginH = 30;
    UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(labelMarginH, kNavigationBarHeight + 20, kScreenWidth - 2 * labelMarginH, 200)];
    [self.view addSubview:labelView];
    
    CATextLayer *textLayer = [CATextLayer layer];
    textLayer.contentsScale = [UIScreen mainScreen].scale;
    textLayer.frame = labelView.bounds;
    [labelView.layer addSublayer:textLayer];
    
    // set text attributes
//    textLayer.foregroundColor = [UIColor blackColor].CGColor;
    textLayer.alignmentMode = kCAAlignmentLeft;
    textLayer.wrapped = true;
    
    NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipiscing \ elit. Quisque massa arcu, eleifend vel varius in, facilisis pulvinar \ leo. Nunc quis nunc at mauris pharetra condimentum ut ac neque. Nunc elementum, libero ut porttitor dictum, diam odio congue lacus, vel \ fringilla sapien diam at purus. Etiam suscipit pretium nunc sit amet \ lobortis";
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];
    
    // choose a font
    UIFont *font = [UIFont systemFontOfSize:15];
    
    //set layer font
    CFStringRef fontName = (__bridge CFStringRef)font.fontName;
    CGFloat fontSize = font.pointSize;
    CTFontRef fontRef = CTFontCreateWithName(fontName, fontSize, NULL);
//    CGFontRef fontRef = CGFontCreateWithFontName(fontName);
//    textLayer.font = fontRef;
    textLayer.fontSize = font.pointSize;
    
    NSDictionary *attribs = @{
                              (__bridge id)kCTForegroundColorAttributeName: (__bridge id)[UIColor blackColor].CGColor,
                              (__bridge id)kCTFontAttributeName: (__bridge id)fontRef
                              };
    [string setAttributes:attribs range:NSMakeRange(0, [text length])];
    
    attribs = @{
                (__bridge id)kCTForegroundColorAttributeName: (__bridge id)[UIColor redColor].CGColor,
                (__bridge id)kCTFontAttributeName: (__bridge id)fontRef,
                (__bridge id)kCTUnderlineStyleAttributeName: @(kCTUnderlineStyleSingle)
                };
    [string setAttributes:attribs range:NSMakeRange(6, 5)];
    
//    CGFontRelease(fontRef);
    CFRelease(fontRef);
    
    // set layer text
    textLayer.string = string;
}

@end
